<template>
  <el-config-provider :locale="zhCn">
    <div class="power-manage">
      <!-- 筛选条件区域 -->
      <filter-form v-model="filterForm" :form-items="formItems" @search="handleSearch" @reset="resetFilter" @update:modelValue="handleFilterChange" />

      <!-- 统计卡片区域 -->
      <div class="statistics-section">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-card shadow="hover" class="statistics-card">
              <div class="card-content">
                <div class="card-header">
                  <span>合计输入Token</span>
                  <el-icon class="card-icon"><Download /></el-icon>
                </div>
                <div class="card-value">{{ statistics.allInPutToken || '0' }} <span class="unit">个</span></div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover" class="statistics-card">
              <div class="card-content">
                <div class="card-header">
                  <span>合计输出Token</span>
                  <el-icon class="card-icon"><Upload /></el-icon>
                </div>
                <div class="card-value">{{ statistics.allOutPutToken || '0' }} <span class="unit">个</span></div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover" class="statistics-card">
              <div class="card-content">
                <div class="card-header">
                  <span>合计费用</span>
                  <el-icon class="card-icon"><Money /></el-icon>
                </div>
                <div class="card-value">{{ statistics.allCoatString || '0' }} <span class="unit">元</span></div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 列表展示区域 -->
      <div class="table-section">
        <el-table :data="tableData" border style="width: 100%" v-loading="loading" class="custom-table">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="主体信息" min-width="200">
            <template #default="{ row }">
              <ai-wechat-info :avatar-url="row.userAvatarUrl || ''" :user-name="row.userName || ''" />
            </template>
          </el-table-column>
          <el-table-column prop="aiInputToken" label="合计输入Token" min-width="120" align="center">
            <template #default="{ row }"> {{ row.aiInputToken }} <span class="unit">个</span> </template>
          </el-table-column>
          <el-table-column prop="aiOutputToken" label="合计输出Token" min-width="120" align="center">
            <template #default="{ row }"> {{ row.aiOutputToken }} <span class="unit">个</span> </template>
          </el-table-column>
          <el-table-column prop="costSring" label="费用" min-width="120" align="center">
            <template #default="{ row }"> {{ row.costSring }} <span class="unit">元</span> </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />
    </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { Upload, Download, Money } from '@element-plus/icons-vue';
import { getComputingPowerList, ComputingPowerListResponse } from '@/api/companyMange/powerMange';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import AiWechatInfo from '@/components/AiWechatInfo/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';

// 筛选表单
const filterForm = ref({
  dateRange: [] as string[]
});

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    label: '时间范围',
    prop: 'dateRange',
    type: 'daterange',
    placeholder: '请选择时间范围',
    valueFormat: 'YYYY-MM-DD',
    startPlaceholder: '开始日期',
    endPlaceholder: '结束日期'
  }
]);

// 统计数据
const statistics = reactive({
  allInPutToken: '0',
  allOutPutToken: '0',
  allCoatString: '0',
  allCoat: '0'
});

// 表格数据
const tableData = ref<any[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);

// 获取数据
const fetchData = async (formData?: Record<string, any>) => {
  const searchData = formData || filterForm.value;

  loading.value = true;
  try {
    let params: { startTime?: string; endTime?: string; current?: number; size?: number } = {
      current: currentPage.value,
      size: pageSize.value
    };

    // 如果选择了时间范围，则添加到参数中
    if (searchData.dateRange && searchData.dateRange.length === 2) {
      const [startTime, endTime] = searchData.dateRange;
      params.startTime = startTime;
      params.endTime = endTime;
    }

    const res = await getComputingPowerList(params);
    const response = res as unknown as ComputingPowerListResponse;
    if (response.code === 200) {
      // 处理新的数据格式
      if (response.data.records) {
        // 新格式：包含分页信息
        tableData.value = response.data.records;
        total.value = response.data.total;
        // 如果返回了统计数据，则更新统计信息
        if (response.data.allMap) {
          Object.assign(statistics, response.data.allMap);
        }
      } else {
        // 兼容旧格式
        tableData.value = response.data.resultList || [];
        total.value = response.data.resultList?.length || 0;
        if (response.data.allMap) {
          Object.assign(statistics, response.data.allMap);
        }
      }
    } else {
      ElMessage.error(response.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = async (formData?: Record<string, any>) => {
  currentPage.value = 1;
  await fetchData(formData);
};

// 重置筛选
const resetFilter = () => {
  filterForm.value.dateRange = [];
  currentPage.value = 1;
  pageSize.value = 10;
  fetchData();
};

// 分页处理
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  fetchData();
};

// 处理筛选条件变化
const handleFilterChange = (val: any) => {
  filterForm.value.dateRange = val.dateRange || [];
};

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style lang="scss" scoped>
.power-manage {
  padding: 20px;
  min-height: calc(100vh - 40px);

  .statistics-section {
    margin-bottom: 16px;

    .statistics-card {
      transition: all 0.3s ease;
      border: none;
      border-radius: 6px;
      overflow: hidden;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      }

      :deep(.el-card__body) {
        padding: 0;
      }

      .card-content {
        padding: 12px 16px;
        background-color: #f8f9fa;

        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
          font-size: 14px;
          color: #606266;
          font-weight: 500;

          .card-icon {
            font-size: 16px;
            color: #409eff;
          }
        }

        .card-value {
          font-size: 20px;
          font-weight: bold;
          color: #303133;
          line-height: 1.2;

          .unit {
            font-size: 14px;
            font-weight: normal;
            color: #909399;
            margin-left: 4px;
          }
        }
      }
    }
  }

  .table-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .custom-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }

      :deep(.el-table__row) {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }
    }

    .unit {
      font-size: 12px;
      color: #909399;
      margin-left: 2px;
    }
  }
}
</style>
